package com.scheduling.order.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scheduling.common.result.Result;
import com.scheduling.order.entity.dto.OrderDTO;
import com.scheduling.order.service.IOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

/**
 * 订单管理控制器
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "订单管理", description = "订单管理相关接口")
@Validated
public class OrderController {

    private final IOrderService orderService;

    @PostMapping
    @Operation(summary = "创建订单", description = "创建新订单，包含客户信息和订单项")
    public Result<OrderDTO> createOrder(@Valid @RequestBody OrderDTO orderDTO) {
        try {
            OrderDTO result = orderService.createOrder(orderDTO);
            return Result.success(result, "订单创建成功");
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }

    @PutMapping("/{orderId}")
    @Operation(summary = "更新订单", description = "更新订单信息")
    public Result<OrderDTO> updateOrder(
            @Parameter(description = "订单ID") @PathVariable @NotBlank String orderId,
            @Valid @RequestBody OrderDTO orderDTO) {
        try {
            orderDTO.setOrderId(orderId);
            OrderDTO result = orderService.updateOrder(orderDTO);
            return Result.success(result, "订单更新成功");
        } catch (Exception e) {
            log.error("更新订单失败: {}", orderId, e);
            return Result.error("更新订单失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{orderId}")
    @Operation(summary = "删除订单", description = "删除订单及其所有订单项")
    public Result<Void> deleteOrder(@Parameter(description = "订单ID") @PathVariable @NotBlank String orderId) {
        try {
            boolean success = orderService.deleteOrder(orderId);
            if (success) {
                return Result.success(null, "订单删除成功");
            } else {
                return Result.error("订单删除失败");
            }
        } catch (Exception e) {
            log.error("删除订单失败: {}", orderId, e);
            return Result.error("删除订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/{orderId}")
    @Operation(summary = "查询订单详情", description = "根据订单ID查询订单详情")
    public Result<OrderDTO> getOrderDetail(@Parameter(description = "订单ID") @PathVariable @NotBlank String orderId) {
        try {
            OrderDTO result = orderService.getOrderDetail(orderId);
            return Result.success(result, "查询成功");
        } catch (Exception e) {
            log.error("查询订单详情失败: {}", orderId, e);
            return Result.error("查询订单详情失败: " + e.getMessage());
        }
    }

    @GetMapping
    @Operation(summary = "分页查询订单", description = "分页查询订单列表，支持条件筛选")
    public Result<Page<OrderDTO>> getOrderPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") long size,
            @Parameter(description = "客户名称") @RequestParam(required = false) String customerName,
            @Parameter(description = "订单状态") @RequestParam(required = false) String status,
            @Parameter(description = "开始日期") @RequestParam(required = false) LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) LocalDate endDate) {
        try {
            Page<OrderDTO> result = orderService.getOrderPage(current, size, customerName, status, startDate, endDate);
            return Result.success(result, "查询成功");
        } catch (Exception e) {
            log.error("分页查询订单失败", e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/status/{status}")
    @Operation(summary = "查询指定状态订单", description = "查询指定状态的订单列表")
    public Result<List<OrderDTO>> getOrdersByStatus(@Parameter(description = "订单状态") @PathVariable @NotBlank String status) {
        try {
            List<OrderDTO> result = orderService.getOrdersByStatus(status);
            return Result.success(result, "查询成功");
        } catch (Exception e) {
            log.error("查询订单失败，状态: {}", status, e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/pending")
    @Operation(summary = "查询待生产订单", description = "查询所有待排产状态的订单")
    public Result<List<OrderDTO>> getPendingOrders() {
        try {
            List<OrderDTO> result = orderService.getPendingOrders();
            return Result.success(result, "查询成功");
        } catch (Exception e) {
            log.error("查询待生产订单失败", e);
            return Result.error("查询待生产订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/overdue")
    @Operation(summary = "查询逾期订单", description = "查询所有逾期未完成的订单")
    public Result<List<OrderDTO>> getOverdueOrders() {
        try {
            List<OrderDTO> result = orderService.getOverdueOrders();
            return Result.success(result, "查询成功");
        } catch (Exception e) {
            log.error("查询逾期订单失败", e);
            return Result.error("查询逾期订单失败: " + e.getMessage());
        }
    }

    @PutMapping("/{orderId}/status")
    @Operation(summary = "更新订单状态", description = "更新指定订单的状态")
    public Result<Void> updateOrderStatus(
            @Parameter(description = "订单ID") @PathVariable @NotBlank String orderId,
            @Parameter(description = "新状态") @RequestParam @NotBlank String status) {
        try {
            boolean success = orderService.updateOrderStatus(orderId, status);
            if (success) {
                return Result.success(null, "订单状态更新成功");
            } else {
                return Result.error("订单状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新订单状态失败: {} -> {}", orderId, status, e);
            return Result.error("更新订单状态失败: " + e.getMessage());
        }
    }

    @PutMapping("/{orderId}/refresh")
    @Operation(summary = "刷新订单进度", description = "重新计算订单的生产进度和状态")
    public Result<Void> refreshOrderProgress(@Parameter(description = "订单ID") @PathVariable @NotBlank String orderId) {
        try {
            orderService.refreshOrderProgress(orderId);
            return Result.success(null, "订单进度刷新成功");
        } catch (Exception e) {
            log.error("刷新订单进度失败: {}", orderId, e);
            return Result.error("刷新订单进度失败: " + e.getMessage());
        }
    }

    @PutMapping("/batch-status")
    @Operation(summary = "批量更新订单状态", description = "批量更新多个订单的状态")
    public Result<Integer> batchUpdateOrderStatus(
            @Parameter(description = "订单ID列表") @RequestBody List<String> orderIds,
            @Parameter(description = "新状态") @RequestParam @NotBlank String status) {
        try {
            int updatedCount = orderService.batchUpdateOrderStatus(orderIds, status);
            return Result.success(updatedCount, "批量更新成功，影响 " + updatedCount + " 个订单");
        } catch (Exception e) {
            log.error("批量更新订单状态失败", e);
            return Result.error("批量更新订单状态失败: " + e.getMessage());
        }
    }
} 